<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/19
 * Time: 10:18
 */

namespace Hrm\Controllers;

use \Admin\Frontend\Controllers\ControllerBase;
use Admin\Models\hrm\XhhrmApprove;
use Admin\Models\hrm\XhhrmDepart;
use Admin\Models\hrm\XhhrmExperience;
use Admin\Models\hrm\XhhrmInterview;
use Admin\Models\hrm\XhhrmResource;
use Admin\Models\hrm\XhhrmStaff;
use Admin\Models\hrm\XhhrmStaffContact;
use Admin\Models\user\XhsysUser;
use Helpers\Assets;
use Helpers\Hrm;
use Helpers\Main;
use Helpers\Template;
use Helpers\Tool;
use Helpers\User;
use Helpers\XhException;
use Modules\Power;
use Phalcon\Mvc\Dispatcher;
use Services\Msg\Msg;

class ResourceController extends ControllerBase
{

    public function beforeExecuteRoute(Dispatcher $dispatcher)
    {
        if (in_array(strtolower($dispatcher->getActionName()), [
            strtolower('index'),
            strtolower('getStaff'),
        ])) {
            return true;
        }
        //检查是否已登陆，否则跳转到登陆页面
        if (!User::isLogin()) {
            Main::goLoginPage();
            return false;
        }
        return true;
    }

    public static $enums = [
        'iEmploySource' => [1 => '网站投递', 2 => '猎头推荐', 3 => '招聘会', 4 => '内部员工推荐'],
        'bMarried' => [1 => '已', 0 => '未'],
        'iWorkStatus' => [
            1 => '兼职',
            2 => '实习',
            3 => '全职',
            4 => '应届',

        ],
        'iStaffStatus' => [
            1 => '在职',
            2 => '离职',
            3 => '退休',
        ],
        'iOfferStatus' => [
            1 => '试用',
            2 => '正式',
            3 => '非正式',
            4 => '其他'
        ],
        'iUserSex' => ['1' => '男', 2 => '女'],
        'mSuggest' => ['复试', '条件尚可但暂不考虑,可纳入后备人才库', '不予以考虑', '试用', '变更岗位试用'],
//        'iRegisterType' => [1 => '本地城镇', 2 => '本地农村', 3 => '外地城镇', 4 => '外地农村' ],
        'iRegisterType' => [
            10 => '本地城镇（主城区）',
            11 => '外地城镇（省内市外）',
            12 => '外地城镇（省外）',
            20 => '本地农村（主城区）',
            21 => '外地农村（省内市外）',
            22 => '外地农村（省外）',
        ],
    ];

    private static $state = [
        0 => '新建',
        1 => '未录取',
        2 => '待入职',
        3 => '未入职',
        4 => '已入职',
        5 => '待录用'
    ];

    /**
     * 获取人力资源
     *
     * @return \Phalcon\Mvc\View
     *
     * create by dale  20180919
     */
    public function indexAction()
    {
        try {
            Assets::easyUI();
            Assets::sweetAlert2();
            Assets::datetimePicker();
            $this->assets->addCss('assets/jquery/jquery.webui-popover.css');
            $this->assets->addJs('assets/jquery/jquery.webui-popover.js');
            Assets::importJs('js/resource/index.js');
            $this->view->pick('resource/index');
            $enums = self::$enums;
            $enums['iWorkStatus'][''] = '工作状态';
            Template::exists('resource', 'list') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109106002));
            $listButtonArr = $formButtonArr = $listSearchArr = array();
            if (Power::exist('Hrm_Resource_Add')) {
                $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_add', 'text' => '新增', 'icon' => 'fa-plus');
            }
            if (Power::exist('Hrm_Resource_Del')) {
                $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash');
            }
            if (Power::exist('Hrm_Resource_Synchronous')) {
                $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_synchronous', 'text' => '同步', 'icon' => 'fa-refresh');
            }
            if (Power::exist('Hrm_Resource_Edit')) {
                $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_state', 'text' => '状态',
                    'class' => 'bt_list_menu');
            }
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_see', 'text' => '查看', 'icon' => 'fa-eye');
            if (Power::exist('Hrm_Resource_SetInterviewFlow')) {
                $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_interviewFlow',
                    'text' => '设置面试流程', 'icon' => 'fa-pencil');
            }
            if (Power::exist('Hrm_Resource_InterviewComment')) {
                $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_interview',
                    'text' => '面试评价', 'icon' => 'fa-comment');
            }
            if (Power::exist('Hrm_Resource_SendSms')) {
                $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_menu_sendSms', 'text' => '发送短信',
                    'class' => 'bt_list_menu');
            }
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_seeQR', 'text' => '获取面试QR', 'icon' => 'fa-eye');
            $state = self::$state;
            $state[''] = '全部';
            $listSearchArr[] = array('type' => 'select', 'id' => 'select_state', 'data' => $state, 'default' => '');
            $listSearchArr[] = array('type' => 'select', 'id' => 'select_sendDisqualify', 'data' => [
                0 => '未录取短信',
                1 => '未发送',
                2 => '已发送'
            ], 'default' => '');
            $listSearchArr[] = array('type' => 'select', 'id' => 'select_sendInvite', 'data' => [
                0 => '邀约短信',
                1 => '未发送',
                2 => '已发送'
            ], 'default' => '');
            $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
            $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找',
                'icon' => 'fa-search', 'style' => 'margin-left:10px');
            return $this->view->setVars(array(
                'staffList' => Template::createList('staffList', 'resource', [
                    'searchToolbar' => Template::createSearchToolBar($listSearchArr, true),
                    'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
                ]),
            ));
        } catch (\Exception $e) {
            return $this->sendViewError(
                $e->getMessage()
            );
        }
    }



    /**
     * 获取人力资源信息
     *
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180919
     */
    public function getResourceAction()
    {
        $key = $this->request->getPost('key', 'string'); //可以为空
        $iDepId = $this->request->getPost('depId', 'string');
        $state  = $this->request->getPost('state', 'string');
        $sourceId = $this->request->getPost('sourceId', 'int');
        $sendInvite = $this->request->getPost('sendInvite', 'int');
        $sendDisqualify = $this->request->getPost('sendDisqualify', 'int');
        try {
            $builder = $this->modelsManager->createBuilder()
                ->columns(['s.iStaffId', 's.sNativePlace', 's.sStaffName', 's.sDepIds','s.sPostName',
                    's.tBirthday', 's.iUserSex', 's.bMarried', 's.sNationName', 's.sIdentityCode',
                    's.sNowAddress', 's.sFamilyAddress', 's.sSelfPhone','s.iState','s.tTime','s.mSignature',
                    's.bSendDisqualify','s.bSendInvite','s.sInterTime'])
                ->from(['s' => 'Admin\Models\hrm\XhhrmResource'])
                ->where('s.bDelete=0');
            if ($sourceId) {
                $builder->andWhere('s.iStaffId = :iStaffId:', ['iStaffId' => $sourceId]);
            } else {
                if ($key) {
                    $builder->andWhere('s.sStaffName like :key: 
                    OR s.sSelfPhone like :key: OR s.sPostName like :key: ', array('key' => '%' . $key . '%'));
                };
                if ($iDepId) {
                    $builder->andWhere('sDepIds LIKE :sDepIds:', array('sDepIds' => '%,' . $iDepId . ',%'));
                }
                if ($state || $state === '0') {
                    $builder->andWhere(' iState = :state:', ['state' => $state]);
                }
                if ($sendDisqualify) {
                    $sendDisqualify -= 1;
                    $builder->andWhere(' bSendDisqualify = :bSendDisqualify:', ['bSendDisqualify' => $sendDisqualify]);
                }
                if ($sendInvite) {
                    $sendInvite -= 1;
                    $builder->andWhere(' bSendInvite = :bSendInvite:', ['bSendInvite' => $sendInvite]);
                }
            }
            $data = Main::runBuilderPage($builder);
            foreach ($data['rows'] as $index => &$row) {
                $row['info'] = '<i class="fa fa-user" style="color:';
                $row['info'] .= $this->resourceColor($row['iState']) . ';" ></i>';
                if ($row['tBirthday'] != null) {
                    $row['iAge'] = $this->getAge($row['tBirthday']);
                }
                if ($row['sDepIds']) {
                    $row['sDepName'] = XhhrmDepart::getDepName($row['sDepIds']);
                }
                $row['iUserSex'] = self::$enums['iUserSex'][$row['iUserSex']];
                $row['bMarried'] = self::$enums['bMarried'][$row['bMarried']];
                $row['iState'] = self::$state[$row['iState']];
                if ($row['bSendDisqualify']) {
                    $row['sendDisqualify'] = '<i class="fa fa-envelope" title="已发送未录取短信" style="color:grey;"></i>';
                }
                if ($row['bSendInvite']) {
                    $row['sendInvite'] = '<i class="fa fa-envelope" title="已发送邀约短信" style="color:#66CC00;"></i>';
                }
                if ($row['sInterTime']) {
                    $row['sInterTime'] = date('Y-m-d H:i', strtotime($row['sInterTime']));
                }
            }
            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 获取职工颜色
     *
     * @param $state
     *
     * @return string
     *
     * create by dale  20180919
     */
    public function resourceColor($state)
    {
        switch ($state) {
            case 1:
                return 'red';  //未录取
            case 2:
                return '#66CC00'; //待入职
            case 3:
                return '#FFCC00';   //未入职
            case 4:
                return '#2baab1'; //已入职
            case 5:
                return 'grey';
            default:
                return 'white';
        }
    }

    /**
     * 获取年龄
     *
     * @param $birthday
     *
     * @return false|string
     *
     * create by dale  20180919
     */
    public function getAge($birthday)
    {
        list($year, $month, $day) = explode("-", $birthday);
        $year_diff = date("Y") - $year;
        $month_diff = date("m") - $month;
        $day_diff = date("d") - $day;
        if ($day_diff < 0 || $month_diff < 0) {
            $year_diff--;
        }
        return $year_diff;
    }



    /**
     * 人力资源tab
     *
     * @return \Phalcon\Mvc\View
     *
     * create by dale  20180918
     */
    public function sourceTabAction()
    {
        $this->view->pick('resource/sourceTab');
        Assets::importJs('js/resource/sourceTab.js');
        $sourceId = $this->request->getQuery('sourceId', 'int');
        if ($sourceId) {
            $info = XhhrmResource::findFirst($sourceId)->toArray();
            if ($info) {
                $this->view->setVar('info', $info);
            }
        }
        return $this->view->setVars([
            'enums' => self::$enums,
            'staffArr' => Hrm::getFlowStaffWithDepName()
        ]);
    }

    /**
     * 保存人力资源
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180919
     */
    public function saveSourceAction()
    {
        try {
            $id = $this->request->getPost('iStaffId', 'int');
            $postData = $this->request->getPost();
            $phone = $this->request->getPost('sSelfPhone', 'string');
            $depId = $this->request->getPost('depId', 'int');
            if ($id) {
                $obj = XhhrmResource::findFirst($id);
            } else {
                $obj = new XhhrmResource();
            }
            if ($phone && !Tool::validPhone($phone)) {
                return $this->sendErrorResponse(500, '手机号格式不正确');
            }
            if (!self::checkPhone($phone, $id)) {
                return $this->sendErrorResponse(500, '该手机号已存在库里');
            };
            $postData = array_filter($postData);

            $obj->assign($postData);
            if ($depId) {
                $depArr = XhhrmDepart::getDepIdArr($depId);
                $sDepIds = ','.implode(',', $depArr).',';
                $obj->sDepIds = $sDepIds;
            }
            if (!$obj->save()) {
                return $this->sendErrorResponse(500, '保存失败');
            }
            return $this->sendJsonResponse(['code' => 200, 'msg' => '保存成功', 'staffId' => $obj->iStaffId], true);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 检查电话是否重复
     *
     * @param $phone
     * @param null $staffId
     *
     * @return bool
     *
     * create by dale  20190226
     */
    public static function checkPhone($phone, $staffId = null)
    {
        $staffArr = XhhrmResource::find([
            'conditions' => 'bDelete = 0 and sSelfPhone = :phone: ',
            'bind'        => ['phone' => $phone]
        ])->toArray();
        if (!$staffArr) {
            return true;
        }
        if ($staffId) {
            if (count($staffArr) == 1 && $staffId == $staffArr[0]['iStaffId']) {
                return true;
            }
        }
        if (count($staffArr) > 1) {
            return false;
        }
        return false;
    }


    /**
     * 删除人才资源库
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180920
     */
    public function delSourceAction()
    {
        try {
            $ids = $this->request->getPost('ids', 'int');
            if (!is_array($ids)) {
                $ids = explode(',', $ids);
            }
            $objArr = XhhrmResource::find([
                'conditions' => 'bDelete = 0 and iStaffId in ({ids:array})',
                'bind'       => ['ids' => $ids]
            ]);
            $this->db->begin();
            foreach ($objArr as $obj) {
                $obj->bDelete = 1 ;
                if (!$obj->save()) {
                    throw new XhException('保存失败');
                }
            }
            $this->db->commit();
            return $this->sendSuccessResponse('保存成功');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }


    /**
     * 经历
     *
     * @param null $tag
     *
     * @return \Phalcon\Mvc\View
     *
     * create by dale  20180919
     */
    public function experienceAction($tag = null)
    {
        $sourceId = $this->request->getQuery('sourceId', 'int');
        if (!$sourceId) {
            $this->sendViewError('未传入人才id');
        }
        $expArr = XhhrmExperience::find([
            'conditions' => 'bDelete = 0 and sTag = :sTag: and iSourceId = :iSourceId:',
            'bind' => ['sTag' => $tag, 'iSourceId' => $sourceId ],
            'order' => 'sStartTime desc'
        ])->toArray();
        $this->view->pick('resource/experience');
        Assets::layUI();
        Assets::importJs('js/resource/experience.js');
        return $this->view->setVars([
            'sourceId' => $sourceId,
            'tag' => $tag,
            'infoArr' => $expArr
        ]);
    }

    /**
     * 经历表单
     *
     * @param $tag
     * @return \Phalcon\Mvc\View
     *
     * create by dale  20180919
     */
    public function expFormAction($tag = null)
    {
        $this->view->pick('resource/expForm');
        Assets::importJs('js/resource/expForm.js');
        $id = $this->request->getQuery('id');
        if ($id) {
            $info = XhhrmExperience::findFirst($id)->toArray();
            if ($info) {
                $this->view->setVar('info', $info);
            }
        }
//        $sourceId = $this->request->getQuery('sourceId', 'int');
        return $this->view->setVars([
            'tag' => $tag,
            'sourceId' => $this->request->getQuery('sourceId', 'int')
        ]);
    }

    /**
     * 保存经历
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180919
     */
    public function saveExperienceAction()
    {
        try {
            $iSEId = $this->request->getPost('iSEId', 'int');
            if ($iSEId) {
                $obj = XhhrmExperience::findFirst($iSEId);
            } else {
                $obj = new XhhrmExperience();
            }
            $obj->assign($this->request->getPost());
            if (!$obj->save()) {
                return $this->sendErrorResponse(500, '保存失败');
            }
            return $this->sendSuccessResponse('保存成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 删除经历
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180919
     */
    public function delExperienceAction()
    {
        try {
            $id = $this->request->getPost('id', 'int');
            if (!$id) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            $obj = XhhrmExperience::findFirst($id);
            if (!$obj) {
                return $this->sendErrorResponse(500, '为找到该记录');
            }
            $obj->bDelete = 1;
            if (!$obj->save()) {
                return $this->sendErrorResponse(500, '保存失败');
            }
            return $this->sendSuccessResponse('保存成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 家庭
     *
     * @return \Phalcon\Mvc\View
     *
     * create by dale  20180920
     */
    public function familyAction()
    {
        $sourceId = $this->request->getQuery('sourceId', 'int');
        if (!$sourceId) {
            $this->sendViewError('未传入人才id');
        }
        $this->view->pick('resource/family');
        Assets::importJs('js/resource/family.js');
        $contact = XhhrmStaffContact::find([
            'conditions' => 'bDelete = 0 and iSourceId = :iSourceId:',
            'bind'       => ['iSourceId' =>  $sourceId]
        ])->toArray();
        if ($contact) {
            $this->view->setVar('familyArr', $contact);
        }
        return $this->view->setVars([
            'sourceId' => $sourceId
        ]);
    }

    /**
     * 家庭表单
     *
     * @return \Phalcon\Mvc\View
     *
     * create by dale  20180920
     */
    public function familyFormAction()
    {
        $sourceId = $this->request->getQuery('sourceId', 'int');
        $this->view->pick('resource/familyForm');
        Assets::importJs('js/resource/familyForm.js');
        $iSCId = $this->request->getQuery('iSCId', 'int');
        if ($iSCId) {
            $info = XhhrmStaffContact::findFirst($iSCId)->toArray();
            $this->view->setVar('info', $info);
        }
        return $this->view->setVars([
            'sourceId' => $sourceId
        ]);
    }

    /**
     * 保存家庭成员
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180920
     */
    public function saveFamilyAction()
    {
        try {
            $id = $this->request->getPost('iSCId', 'int');
            $postData = $this->request->getPost();
            if ($id) {
                $obj = XhhrmStaffContact::findFirst($id);
            } else {
                $obj = new XhhrmStaffContact();
            }
            $obj->assign($postData);
            if (!$obj->save()) {
                return $this->sendErrorResponse(500, '保存失败');
            }
            return $this->sendSuccessResponse('保存成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 删除家庭成员
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180920
     */
    public function delFamilyAction()
    {
        try {
            $id = $this->request->getPost('id', 'int');
            if (!$id) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            $obj = XhhrmStaffContact::findFirst($id);
            if (!$obj) {
                return $this->sendErrorResponse(500, '为找到该记录');
            }
            $obj->bDelete = 1;
            if (!$obj->save()) {
                return $this->sendErrorResponse(500, '保存失败');
            }
            return $this->sendSuccessResponse('保存成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 面试填写
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by dale  20180921
     */
    public function interviewTabAction()
    {
        try {
            $sourceId = $this->request->getQuery('sourceId', 'int');
            if (!$sourceId) {
                return $this->sendViewError('缺少参数');
            }
            $this->view->pick('resource/interviewTab');
            Assets::select2();
            Assets::importJs('js/resource/interviewTab.js');
            $infoArr = XhhrmInterview::find([
                'conditions' => 'bDelete= 0 and iSourceId = :iSourceId:',
                'bind'       => ['iSourceId' => $sourceId]
            ])->toArray();
            if ($infoArr) {
                $index = array_column($infoArr, 'iIndex');
                $userId = Main::getLoginUserInfo('userId');
                $activeTabIndex = 0;
                if ($userId) {
                    foreach ($infoArr as $info) {
                        if ($info['iInterviewer'] == $userId && !$info['mSuggest']) {
                            if (!$activeTabIndex) { //优先级 1 > 2 > 3
                                $activeTabIndex = $info['iIndex'];
                            }
                        }
                    }
                }
                $this->view->setVar('activeTabIndex', $activeTabIndex);
                $this->view->setVar('maxIndex', max($index));
                $this->view->setVar('info', $infoArr);
            }
            return $this->view->setVars([
                'sourceId' => $sourceId,
                'mSuggest' => self::$enums['mSuggest'],
                'staffArr' => XhhrmStaff::getStaff(),
            ]);
        } catch (\Exception $e) {
            return $this->sendViewError(
                $e->getMessage()
            );
        }
    }

    /**
     * 获取下一个负责人
     *
     * @param $sourceId
     * @param int $index 可以指定第几个之后
     *
     * @return bool|int
     * @throws XhException
     *
     * create by dale  20181107
     */
    public function getNextInterviewCharge($sourceId, $index = 0)
    {
        if (!$sourceId) {
            throw new XhException('未传入sourceId');
        }
        $interview = XhhrmInterview::findFirst([
            'columns'    => 'iInterviewer',
            'conditions' => 'iSourceId = :iSourceId: and iIndex > :iIndex: and iInterviewer is not null',
            'bind'       => ['iIndex' => $index, 'iSourceId' => $sourceId],
            'order'      => 'iIndex'
        ]);
        if (!$interview) {
            return false;
        }

        return $interview->iInterviewer;
    }


    /**
     * 保存面试信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180925
     * modify by dale 20181108   添加面试链传递消息至下一个负责人
     */
    public function saveInterviewAction()
    {
        try {
            $id = $this->request->getPost('iHIId', 'int');
            $postData = $this->request->getPost();
            if (!$postData['iSourceId'] || !$postData['mSuggest']) {
                return $this->sendErrorResponse(400, '缺少必要参数');
            }

            if ($id) {
                $obj = XhhrmInterview::findFirst($id);
            } else {
                $obj = new XhhrmInterview();
            }
            $checkCanUseArr = XhhrmInterview::find([
                'columns'    => 'iIndex,mSuggest',
                'conditions' => 'bDelete = 0 and iSourceId = :iSourceId:',
                'bind'       => ['iSourceId' => $postData['iSourceId']]
            ])->toArray();
            if ($checkCanUseArr) {
                foreach ($checkCanUseArr as $checkCan) {
                    if ($checkCan['iIndex'] != $postData['iIndex']
                         && ($checkCan['mSuggest'] && $checkCan['mSuggest'] != '复试')) {
                        return $this->sendErrorResponse('400', '此人面试已经完结');
                    }
                }
            }
            $this->db->begin();
            $obj->assign($postData);
            if (!$obj->save()) {
                $this->db->rollback();
                return $this->sendErrorResponse(500, '保存失败');
            }
            $resource = XhhrmResource::findFirst($obj->iSourceId);
            if (!$resource) {
                return $this->sendErrorResponse(500, '为找到对应人才记录');
            }
//            var_dump($obj->mSuggest);die;
            if (in_array($obj->mSuggest, [
                    '试用',
                    '变更岗位试用',
                    '不予以考虑',
                    '条件尚可但暂不考虑,可纳入后备人才库'
                ])) {
                $time = date('Y-m-d');
                if (in_array($obj->mSuggest, ['试用', '变更岗位试用'])) {
                    $state = 5;
                    $desc  = '面试录取,待录入录用信息';
                } elseif (in_array($obj->mSuggest, [
                    '不予以考虑',
                    '条件尚可但暂不考虑,可纳入后备人才库'
                ])) {
                    $state = 1;
                    $desc  = '面试未录取';
                }
                $resource->tTime = $time;
                $resource->iState = $state;
                if ($resource->sTime == null) {
                    $resource->sTime = json_encode(
                        [
                            [   'time' => $time,
                                'state' => $state,
                                'desc' => $desc,
                                'operator' => Main::getLoginUserInfo('userId'),
                                'operateTime' => date("Y-m-d H:i:s", time())
                            ]
                        ]
                    );
                } else {
                    $arr = json_decode($resource->sTime, true);
                    $arr[] = [
                        'time' => $time,
                        'state' => $state,
                        'desc'=> $desc,
                        'operator' => Main::getLoginUserInfo('userId'),
                        'operateTime' => date("Y-m-d H:i:s", time())
                    ];
                    $resource->sTime = json_encode($arr);
                }
                if (!$resource->save()) {
                    $this->db->rollback();
                    return $this->sendErrorResponse(500, '人才库信息更新失败');
                }
//                Msg::taskOperator()->done('hrm', 'interviewer', $obj->iSourceId, 'interviewer'.$obj->iIndex);//流程终结
            } else { //复试
//                $sendToNextChargeId = $this->getNextInterviewCharge($obj->iSourceId, $obj->iIndex);
//                Msg::taskOperator()->done('hrm', 'interviewer', $obj->iSourceId, 'interviewer'.$obj->iIndex);
//                if ($sendToNextChargeId !== false) {//给下一个发送信息
//                    $task = Msg::taskCreator('hrm', 'interviewer', $obj->iSourceId);
//                    $task->setOperate('interviewer'. ($obj->iIndex + 1))
//                        ->setTitle('面试通知')
//                        ->setUrl('hrm/resource/interviewQR?scoruceId=' . $obj->iSourceId)
//                        ->addReceiver($sendToNextChargeId)
//                        ->setViewMode($task::VIEW_MODAL)
//                        ->send();
//                } else {
//                    throw new XhException('面试链已结束，但是仍未决定此人去留');
//                }
            }
            $this->db->commit();
            return $this->sendSuccessResponse('保存成功');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 录用信息
     *
     * @return \Phalcon\Mvc\View
     *
     * create by dale  20180926
     */
    public function employAction()
    {
        try {
            $sourceId = $this->request->getQuery('sourceId', 'int');
            if (!$sourceId) {
                return $this->sendViewError('缺少参数');
            }
            $this->view->pick('resource/employ');
            Assets::select2();
            Assets::layUI();
            Assets::importJs('js/resource/employ.js');
            $this->view->setVar('showEmployCheck', false);
            $this->view->setVar('depPower', false);
            if ($sourceId) {
                $info = XhhrmResource::findFirst($sourceId)->toArray();
                if ($info['sDepIds']) {
                    $depIdArr = array_values(array_filter(explode(',', $info['sDepIds'])));
                    $depId = Tool::getValue($depIdArr, 0, null);
                    if ($depId) {
                        $info['depId'] = $depId;
                        $this->view->setVar('showEmployCheck', true);
                        $depTag = Tool::getValue(array_values(Hrm::getDepIdTagRelation('depId', [$depId])), 0);
                        if ($depTag) {
                            $depPower = $this->hasCheckPower('dep', $depTag, 'Hrm_Resource_EmployCheck');
                            $this->view->setVar('depPower', $depPower);
                        }
                    }
                }
                $this->view->setVar('info', $info);
                $approveArr = XhhrmApprove::find([
                    'conditions' => 'bDelete = 0 and iTargetId = :iTargetId: and sType = :sType:',
                    'bind'       => ['iTargetId' => $sourceId, 'sType' => 'employ'],
                ])->toArray();
                if ($approveArr) {
                    Main::runUserName($approveArr, ['iUserId' => 'sUserName'], false);
                    $approveArr = array_column($approveArr, null, 'sVerifier');
                    $this->view->setVar('approveArr', $approveArr);
                }
            }
            //resourcePower
            $resourcePower = $this->hasCheckPower('resource', 'XHRLB', 'Hrm_Resource_EmployCheck');
            $this->view->setVar('resourcePower', $resourcePower);
            $managerPower = $this->hasCheckPower('manager', '', '');
            $this->view->setVar('managerPower',$managerPower);
            return $this->view->setVars([
                'sourceId' => $sourceId,
                'registerType' => self::$enums['iRegisterType'],
                'depArr' => XhhrmDepart::getDepEnum(),
            ]);
        } catch (\Exception $e) {
            return $this->sendViewError(
                $e->getMessage()
            );
        }
    }

    /**
     * 验证权限
     *
     * @param $type
     * @param string $depTag
     * @param string $powerTag
     *
     * @return bool
     * @throws XhException
     *
     * create by dale  20181112
     */
    public function hasCheckPower($type, $depTag = '', $powerTag = '')
    {
        if (User::isAdmin()) {
            return true;
        }
        if (in_array($type, ['dep', 'resource'])) {
            if (!$depTag) {
                throw new XhException('部门标识必传');
            }

            $dep = XhhrmDepart::findFirst([
                'column'     => 'iDepId',
                'conditions' => 'bDelete = 0 and sTag = :sTag:',
                'bind'       => ['sTag' => $depTag]
            ]);
            if (!$dep) {
                throw new XhException('未找到该标识的部门');
            }
            $depId = $dep->iDepId;

            $userId = Main::getLoginUserInfo('userId');
            $sql = "select iUserId from XHHrm_Staff  WHERE find_in_set('".$depId."',sDepIds) and bDelete = 0 and iUserId = {$userId} ";
            $checkInDep = $this->db->fetchOne($sql);
//            if ($type == 'resource') {
//                var_dump($checkInDep);die;
//            }
            if (!$checkInDep) {  //判断是否在部门
                return false;
            }
            if ($powerTag) {
                if (!Power::exist($powerTag)) {
                    return false;
                }
            }
            return true;
        } elseif (in_array($type, ['manager'])) {
            $hrmConfig = Main::getConfigByName('hrm');
            if (!$hrmConfig) {
                throw new XhException('hrm配置项不存在');
            }
            $manager = Tool::getValue($hrmConfig, 'manager');
            if (!$manager) {
                throw new XhException('hrm->manager配置项不存在');
            }
            $managerArr = explode(',', $manager);
            $staff = XhhrmStaff::findFirst([
                'columns'    => 'sSelfPhone',
                'conditions' => 'bDelete = 0 and iUserId = :iUserId:',
                'bind'       => ['iUserId' => Main::getLoginUserInfo('userId')]
            ]);
            if (!$staff) {
                return false;
            }
            if (!$staff->sSelfPhone) {
                return false;
            }
            if (in_array(Main::getLoginUserInfo('logonName'), $managerArr) || in_array($staff->sSelfPhone, $managerArr)) {
                return true;
            }
            return false;
        } else {
            throw new XhException('未知type类型');
        }
    }




    /**
     * 保存审批
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181008
     */
    public function saveApproveAction()
    {
        try {
            $postData =$this->request->getPost();
            $iRAId = $this->request->getPost('iRAId', 'int');
            if ($iRAId) {
                $obj = XhhrmApprove::findFirst($iRAId);
            } else {
                $obj = new XhhrmApprove();
                $obj->iUserId = Main::getLoginUserInfo('userId');
            }
            $obj->sDate = date('Y-m-d');
            $obj->assign($postData);
            if (!$obj->save()) {
                return $this->sendErrorResponse(500, '保存失败');
            }
            return $this->sendSuccessResponse('保存成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 保存入职
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181012
     */
    public function saveEntryAction()
    {
        try {
            $id = $this->request->getPost('id');
            $time  = $this->request->getPost('time');
            $desc  = $this->request->getPost('desc');
            if (!$id || !$time) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            $this->db->begin();
            $obj = XhhrmResource::findFirst($id);
            if (!$obj->sStaffName || !$obj->sIdentityCode) {
                return $this->sendErrorResponse(500, '缺少身份证号码或者名字');
            }
            if ($obj->iState == 4) {
                return $this->sendErrorResponse(400, '该员工已入职,如需更新数据，请联系管理手动同步');
            }

            if ($obj->sTime == null) {
                $obj->sTime = json_encode([['time'=>$time,'state'=>4,'desc'=>$desc,'operator'=>Main::getLoginUserInfo('userId'),'operateTime'=>date("Y-m-d H:i:s",time())]]);
            } else {
                $arr = json_decode($obj->sTime,true);
                $arr[] = ['time'=>$time,'state'=>4,'desc'=>$desc,'operator'=>Main::getLoginUserInfo('userId'),'operateTime'=>date("Y-m-d H:i:s",time())];
                $obj->sTime = json_encode($arr);
            }
            $obj->iState = 4;
            $obj->tTime = $time;
            if (!$obj->save()) {
                return $this->sendSuccessResponse('保存成功');
            }
            $staff = $obj->toArray();
            $staff['iStaffId']  = null;
            $staff['tHireDate'] = $time;
            $newObj = XhhrmStaff::findFirst([
                'conditions' => 'bDelete=0 AND sStaffName=:sStaffName: AND sIdentityCode=:sIdentityCode:',
                'bind' => array('sStaffName' => $staff['sStaffName'], 'sIdentityCode' => $staff['sIdentityCode'])
            ]);
            if (!$newObj) {
                $newObj = new XhhrmStaff();
                $newObj->assign($staff);
                $newObj->sCreateMode = 'resource_entry';
                $newObj->iSourceId = $obj->iStaffId;
                $newObj->iStaffStatus = 1; //在职状态
                if (!$newObj->save()) {
                    return $this->sendErrorResponse(500, '职工信息保存失败');
                }
                $user = XhsysUser::findFirst([
                    'conditions' => 'bDelete=0 AND sSelfPhone=:phone: AND sUserName = :name:',
                    'bind' => ['phone' => $newObj->sSelfPhone, 'name' => $newObj->sStaffName],
                ]);
                if (!$user) {
                    $res = $this->createNewAccount($newObj->sSelfPhone, $newObj->sStaffName);
                    if (!$res) {
                        return $this->sendErrorResponse(500, '账号创建失败');
                    }
                    $user = XhsysUser::findFirst([
                        'conditions' => 'bDelete=0 AND sSelfPhone=:phone: AND sUserName = :name:',
                        'bind' => ['phone' => $newObj->sSelfPhone, 'name' => $newObj->sStaffName],
                    ]);
                }
                $newObj->iUserId = $user->iUserId;
                if (!$newObj->save()) {
                    return $this->sendErrorResponse(500, '关联失败');
                }
            } else { //已经入职过了
                $newObj->tHireDate = $time;
                $newObj->iStaffStatus = 1; //在职状态
                if (!$newObj->save()) {
                    throw new XhException('离职员工恢复失败');
                }
                if ($newObj->iUserId) {
                    $user = XhsysUser::findFirst($newObj->iUserId);
                    if ($user) {
                        if ($user->bDisable == 1) {
                            $user->bDisable = 0;
                            if (!$user->save()) {
                                throw new XhException('账号解除禁用');
                            }
                        }
                    }
                }
            }
            //经历
            $experienceArr = XhhrmExperience::find([
                'conditions' => 'bDelete = 0 and iSourceId = :iSourceId:',
                'bind'       => ['iSourceId' => $obj->iStaffId],
            ]);
            foreach ($experienceArr as $experience) {
                if (!$newObj->iStaffId) {
                    throw new XhException('没有创建职工');
                }
                $experience->iStaffId = $newObj->iStaffId;
                if (!$experience->save()) {
                    throw new XhException('经历修改失败');
                }
            }
            //面试
            $interviewArr = XhhrmInterview::find([
                'conditions' => 'bDelete = 0 and iSourceId = :iSourceId:',
                'bind'       => ['iSourceId' => $obj->iStaffId],
            ]);
            foreach ($interviewArr as $interview) {
                if (!$newObj->iStaffId) {
                    throw new XhException('没有创建职工');
                }
                $interview->iStaffId = $newObj->iStaffId;
                if (!$interview->save()) {
                    throw new XhException('面试修改失败');
                }
            }
            //家庭
            $contactArr = XhhrmStaffContact::find([
                'conditions' => 'bDelete = 0 and iSourceId = :iSourceId:',
                'bind'       => ['iSourceId' => $obj->iStaffId],
            ]);
            foreach ($contactArr as $contact) {
                if (!$newObj->iStaffId) {
                    throw new XhException('没有创建职工');
                }
                $contact->iStaffId = $newObj->iStaffId;
                if (!$contact->save()) {
                    throw new XhException('面试修改失败');
                }
            }
            $this->db->commit();
            return $this->sendSuccessResponse('入职成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }



    /**
     * 设置面试流程
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by dale  20181106
     */
    public function interviewerFlowAction()
    {
        try {
            $sourceId  = $this->request->getQuery('sourceId', 'int');
            if (!$sourceId) {
                return $this->sendViewError('缺少必要参数sourceId');
            }
            Assets::select2();
            $this->view->pick('resource/interviewerFlow');
            Assets::importJs('js/resource/interviewerFlow.js');
            $interviewerArr = XhhrmInterview::find([
                'conditions' => 'bDelete = 0 and iSourceId = :iSourceId:',
                'bind'       => ['iSourceId' => $sourceId],
                'order'      => 'iIndex asc',
            ])->toArray();
            if ($interviewerArr) {
                $index = array_column($interviewerArr, 'iIndex');
                $this->view->setVar('maxIndex', max($index));
                $this->view->setVar('interviewerArr', $interviewerArr);
            }
            return $this->view->setVars([
                'staffArr' => XhhrmStaff::getStaff(),
                'sourceId' => $sourceId
            ]);
        } catch (\Exception $e) {
            return $this->sendViewError(
                $e->getMessage()
            );
        }
    }

    /**
     * 保存人力资源信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181106
     */
    public function saveInterviewerAction()
    {
        try {
            $postData = $this->request->getPost('interviewArr');
            $this->db->begin();
            $sourceId = null;
            $changeArr = [];
            foreach ($postData as $row) {
                $bAdd = false;
                if ($row['iHIId']) {
                    $obj = XhhrmInterview::findFirst($row['iHIId']);
                } else {
                    $bAdd = true;
                    $obj = new XhhrmInterview();
                }
                if ($obj->iInterviewer == @$row['iInterviewer']) {
                    continue;
                }
                $sourceId = $row['iSourceId'];//iSourceId
                $obj->assign($row);
                if (!$obj->save()) {
                    throw new XhException('保存失败');
                }
                $changeArr[$obj->iIndex] = $bAdd ? 'add' : 'modify';
            }
            if ($changeArr) {
//                foreach ($changeArr as $index => $operateType) {
//                    if ($index == 1) { //第一个面试官修改或创建
//                        if ($operateType == 'modify') { //修改第一条
//                            Msg::taskOperator()->scrap('hrm', 'interviewer', $sourceId, 'interviewer'.$index);
//                        }
//                        $sendToNextChargeId = $this->getNextInterviewCharge($sourceId, 0);
//                        if ($sendToNextChargeId !== false) {
//                            $task = Msg::taskCreator('hrm', 'interviewer', $sourceId);
//                            $task->setOperate('interviewer'.$index)
//                                ->setTitle('面试通知')
//                                ->setUrl('hrm/resource/interviewQR?scoruceId=' . $sourceId)
//                                ->addReceiver($this->getNextInterviewCharge($sourceId, 0))
//                                ->setViewMode($task::VIEW_MODAL)
//                                ->send();
//                        }
//                    } else {//修改
//                        if ($operateType == 'modify') { //修改第n条，则先废弃一遍
//                            Msg::taskOperator()->scrap('hrm', 'interviewer', $sourceId, 'interviewer'.$index);
//                        }
//                    }
//                }
            }
            $this->db->commit();
            return $this->sendSuccessResponse('保存成功');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }




    /**
     * 同步信息人才库信息到入职信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181107
     */
    public function synchronousInfoAction()
    {
        try {
            $this->db->begin();
            $sourceId = $this->request->getPost('sourceId', 'string');
            $resource = XhhrmResource::findFirst($sourceId);
            if ($resource->iState != 4) {
                return $this->sendErrorResponse(500, '只能同步已入职职工数据');
            }
            if (!$resource) {
                return $this->sendErrorResponse(500, '未找到该记录');
            }
            $check = XhhrmStaff::count([
                'conditions' => 'bDelete= 0 and sStaffName = :staffName: and sIdentityCode = :sIdentityCode:',
                'bind'       => ['sIdentityCode' => $resource->sIdentityCode, 'staffName' => $resource->sStaffName]
            ]);
            if ($check > 1) {
                return $this->sendErrorResponse(500, '此人存在大于一条职工信息');
            }
            $staffObj = XhhrmStaff::findFirst([
                 'conditions' => 'bDelete = 0 and sStaffName = :staffName: and sIdentityCode = :sIdentityCode:',
                 'bind'       => ['sIdentityCode' => $resource->sIdentityCode, 'staffName' => $resource->sStaffName],
            ]);
            if (!$staffObj) {
                $staffObj = new XhhrmStaff();
                $staffObj->sCreateMode = 'resource_synchronous';
            }
            $resourceData = $resource->toArray();
            $resourceData['iSourceId'] = $resourceData['iStaffId'];
            array_filter($resourceData);
            unset($resourceData['iStaffId']);
            $staffObj->assign($resourceData);
            if (!$staffObj->save()) {
                throw new XhException('保存失败');
            }
            //经历
            $experienceArr = XhhrmExperience::find([
                'conditions' => 'bDelete = 0 and iSourceId = :iSourceId:',
                'bind'       => ['iSourceId' => $resource->iStaffId],
            ]);
            foreach ($experienceArr as $experience) {
                if (!$staffObj->iStaffId) {
                    throw new XhException('没有创建职工');
                }
                $experience->iStaffId = $staffObj->iStaffId;
                if (!$experience->save()) {
                    throw new XhException('经历修改失败');
                }
            }
            //面试
            $interviewArr = XhhrmInterview::find([
                'conditions' => 'bDelete = 0 and iSourceId = :iSourceId:',
                'bind'       => ['iSourceId' => $resource->iStaffId],
            ]);
            foreach ($interviewArr as $interview) {
                if (!$staffObj->iStaffId) {
                    throw new XhException('没有创建职工');
                }
                $interview->iStaffId = $staffObj->iStaffId;
                if (!$interview->save()) {
                    throw new XhException('面试修改失败');
                }
            }
            //家庭
            $contactArr = XhhrmStaffContact::find([
                'conditions' => 'bDelete = 0 and iSourceId = :iSourceId:',
                'bind'       => ['iSourceId' => $resource->iStaffId],
            ]);
            foreach ($contactArr as $contact) {
                if (!$staffObj->iStaffId) {
                    throw new XhException('没有创建职工');
                }
                $contact->iStaffId = $staffObj->iStaffId;
                if (!$contact->save()) {
                    throw new XhException('面试修改失败');
                }
            }
            $this->db->commit();
            return $this->sendSuccessResponse('同步成功');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 验证员工是否入职
     *
     * @param $sStaffName
     * @param $sIdentityCode
     *
     * @return bool
     *
     * create by dale  20181012
     */
    public function checkStaff($sStaffName, $sIdentityCode)
    {
        $checked = XhhrmStaff::findFirst([
            'conditions' => 'bDelete=0 AND sStaffName=:sStaffName: AND sIdentityCode=:sIdentityCode:',
            'bind' => array('sStaffName' => $sStaffName, 'sIdentityCode' => $sIdentityCode)
        ]);
        if ($checked) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 新建员工
     *
     * @param $phoneNum
     * @param $staffName
     * @param string $pwd
     *
     * @return bool
     * @throws \Exception
     *
     * create by dale  20181012
     */
    private function createNewAccount($phoneNum, $staffName, $pwd = '123456')
    {
        $user = new XhsysUser();
        $user->sLogonName   = $phoneNum;
        $user->sUserName    = $staffName;
        $user->sLogonPwd    = strtoupper(md5($pwd));
        $user->sSelfPhone   = $phoneNum;
        $user->iUserType    = 5;
        $user->iSchoolId    = 1;
        $user->bCompany     = 1;
        return $user->insertAfterOld();
    }

    /**
     * 获取应聘者信息二维码
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by dale  20181108
     */
    public function interviewQRAction()
    {
        try {
            $sourceId = $this->request->getQuery('sourceId', 'string');
            $this->view->pick('resource/interviewQR');
            $baseSrc = Tool::getQRBase64Uri(Tool::buildUrl('hrm/resource/readInterview', ['sourceId' => $sourceId]));
            return $this->view->setVars([
                'baseSrc' =>  $baseSrc
            ]);
        } catch (\Exception $e) {
            return $this->sendViewError($e->getMessage());
        }
    }



    /**
     * 面试信息只读页面
     *
     * @return \Phalcon\Mvc\View
     *
     * create by dale  20181107
     */
    public function readInterviewAction()
    {
        $sourceId = $this->request->getQuery('sourceId', 'string');
        if (!$sourceId) {
            return $this->sendViewError('未传入职工id');
        }
        $this->view->pick('resource/readInterview');
        Assets::layUI();
        Assets::sweetAlert2();
        Assets::easyUIMobile();
        Assets::importJs('js/resource/readInterview.js');
        $info = XhhrmResource::findFirst($sourceId);
        if (!$info) {
            return $this->sendViewError('未找到该职工记录');
        }
        $info = $info->toArray();
        if ($info['iRecStaff']) {
            $staff = XhhrmStaff::findFirst([
                'columns'    => 'sStaffName',
                'conditions' => 'iStaffId = :iRecStaff: and bDelete= 0',
                'bind'       => ['iRecStaff' => $info['iRecStaff']]
            ]);
            if ($staff) {
                $info['iRecStaff'] = $staff->sStaffName;
            }
        }
        Tool::runEnum($info, self::$enums);
        $experience = XhhrmExperience::find([
            'conditions' => 'iSourceId = :iSourceId: and bDelete = 0',
            'bind'       => ['iSourceId' => $sourceId],
            'order'      => 'sTag,sStartTime desc'
        ])->toArray();
        $contact = XhhrmStaffContact::find([
            'conditions' => 'iSourceId = :iSourceId: and bDelete = 0',
            'bind'       => ['iSourceId' => $sourceId],
        ])->toArray();
        $arr = [
            'tchHistory' => [],
            'workHistory' => [],
            'itemHistory' => [],
            'family' => [],
        ];
        if ($experience) {
            foreach ($experience as $row) {
                if ($row['sTag'] == 'item') {
                    $arr['itemHistory'][] = $row;
                } else if ($row['sTag'] == 'lean') {
                    $arr['tchHistory'][] = $row;
                } else if ($row['sTag'] == 'work') {
                    $arr['workHistory'][] = $row;
                }
            }
        }
        if ($contact) {
            foreach ($contact as $row) {
                $arr['family'][] = $row;
            }
        }
        $info = array_merge($info, $arr);
        if ($info) {
            $this->view->setVar('info', $info);
        }
        $userId = Main::getLoginUserInfo('userId');
        $interviewArr = XhhrmInterview::find([
            'conditions' => 'bDelete= 0 and iSourceId = :iSourceId: and iInterviewer = :iInterviewer:',
            'bind'       => ['iSourceId' => $sourceId, 'iInterviewer' => $userId],
            'order'      => 'iIndex'
        ])->toArray();
        if (!$interviewArr) {
           $this->view->setVar('showComment', false);
        } else {
            $this->view->setVar('showComment', true);
            if (count($interviewArr) == 1) {
                $this->view->setVar('interviewInfo', $interviewArr[0]);
            } else {
                $currentInterview = null;
                foreach ($interviewArr as $interview) {
                    if (!$interview['mSuggest'] && !$currentInterview) { //currentViewer还未赋值
                        $currentInterview = $interview;
                    }
                }
                if (!$currentInterview) {
                    $currentInterview = end($interviewArr);
                }
                $this->view->setVar('interviewInfo', $currentInterview);
            }
        }

        return $this->view->setVars([
            'enums' => self::$enums,
            'mSuggest' => self::$enums['mSuggest'],
        ]);
    }

    /**
     * 发送短信
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20190226
     */
    public function sendStaffSmsAction()
    {
        $type = $this->request->getPost('type', 'string');
        $ids  = $this->request->getPost('ids');
        if (!$type || !$ids || !is_array($ids)) {
            return $this->sendErrorResponse(400, '缺少参数或者格式不匹配');
        }
        if (!in_array($type, ['invite', 'unUse'])) {
            return $this->sendErrorResponse(400, '未知发送短信类型');
        }
        $infoEnums = [
            'invite' => [
                1 => "%s先生，您好！浙江学海教育科技有限公司诚邀您参加我们的%s岗位面试，面试时间：%s 面试地址： 浙江省杭州市余杭区五常大道133号凯诚金座2号楼6楼，届时请携带上个人简历准时参加面试，谢谢!",
                2 => "%s女士，您好！浙江学海教育科技有限公司诚邀您参加我们的%s岗位面试，面试时间：%s 面试地址： 浙江省杭州市余杭区五常大道133号凯诚金座2号楼6楼，届时请携带上个人简历准时参加面试，谢谢!"
            ],
            'unUse' => [
                1 => "%s先生，您好！非常感谢您参加我们公司%s岗位的应聘，您的简历给我们留下了非常深刻的印象，但经综合评估后，非常遗憾通知您没有通过我们的面试，我们已将您的简历存档，日后如果有合适的职位我们会提前跟您联系，再次感谢您对学海的支持。",
                2 => "%s女士，您好！非常感谢您参加我们公司%s岗位的应聘，您的简历给我们留下了非常深刻的印象，但经综合评估后，非常遗憾通知您没有通过我们的面试，我们已将您的简历存档，日后如果有合适的职位我们会提前跟您联系，再次感谢您对学海的支持。",
            ]
        ];
        $objArr = XhhrmResource::find([
            'conditions' => 'bDelete = 0 and iStaffId in ({ids:array})',
            'bind'       => ['ids' => $ids]
        ]);
        if (!$objArr) {
            return $this->sendErrorResponse(400, '未找到人才记录');
        }
        try {
            $errorArr = [];
            $total = count($objArr->toArray());
            $errorNum = 0;
            $successNum = 0;
            $successArr = [];
            foreach ($objArr as $obj) {
                $item = [
                    'id'   => $obj->iStaffId,
                    'name' => $obj->sStaffName,
                    'post' => $obj->sPostName,
                    'sex' => $obj->iUserSex,
                    'phone' => $obj->sSelfPhone,
                    'type'  => $type,
                ];
                if ($type == 'invite') {
                    if ($obj->sInterTime) {
                        $item['time'] = date('Y-m-d H:i', strtotime($obj->sInterTime));
                    } else {
                        $item['time'] = strtotime($obj->sInterTime);
                    }
                }
                if ($type == 'invite') {
                    if (!$obj->sStaffName || !$obj->sPostName || !$obj->iUserSex || !$obj->sInterTime || !$obj->sSelfPhone) {
                        $item['errorLog'] = '缺少参数';
                        $errorArr[] = $item;
                        $errorNum++;
                        continue;
                    }
                    $info = sprintf($infoEnums[$type][$obj->iUserSex], $obj->sStaffName, $obj->sPostName, $item['time']);
                } elseif ($type == 'unUse') {
                    if (!$obj->sStaffName || !$obj->sPostName || !$obj->iUserSex || !$obj->sSelfPhone) {
                        $item['errorLog'] = '缺少参数';
                        $errorArr[] = $item;
                        $errorNum++;
                        continue;
                    }
                    $info = sprintf($infoEnums[$type][$obj->iUserSex], $obj->sStaffName, $obj->sPostName);
                }
                try {
                    Main::sendSMS($obj->sSelfPhone, $info);
                    if ($type == 'invite') {
                        $obj->bSendInvite = 1;
                    } elseif ($type == 'unUse') {
                        $obj->bSendDisqualify = 1;
                    }
                    if (!$obj->save()) {
                        throw new \Exception('短信发送成功，数据保存出错');
                    }
                    $successNum++;
                    $item['smsInfo'] = $info;
                    $successArr[] = $item;
                } catch (\Exception $e) {
                    $item['smsInfo'] = $info;
                    $item['errorLog'] = $e->getMessage();
                    $errorArr[] = $item;
                    $errorNum++;
                    continue;
                }
            }
            return $this->sendJsonResponse([
                'code' => 200,
                'successArr' => $successArr,
                'errorArr'  => $errorArr,
                'msg'  => "共执行{$total}次，成功{$successNum}次，失败{$errorNum}次。"
            ], true);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }


//    public function testAction()
//    {
//        var_dump(Hrm::getDepUserIdByDepId([1]));die;
//    }
    
}